package web.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public class EhcacheUtil {
	
	
	 private static final String path = "../../ehcache.xml"; // EHCache 的配置文件地址 classpath:
	 
	  private CacheManager cacheManager;
	 
	  private static EhcacheUtil ehCache;
	/* 
	  private EhcacheUtil(String path) {
		  cacheManager = CacheManager.create(getClass().getResource(path));
	  } */
	  private EhcacheUtil() {
		  cacheManager = CacheManager.create();
	  }
	  public static EhcacheUtil getInstance() {
	    if (ehCache == null) {
	      ehCache = new EhcacheUtil();
	    }
	    return ehCache;
	  }
	 
	  /**
	   * 缓存一个对象
	   * 
	   * @param cacheName
	   *      缓存的名字
	   * @param key
	   *      缓存的KEY
	   * @param value
	   *      缓存的值
	   *  PUT 写入缓存
	   *  User user=userSerivce.getUserInfo(Integer.valueOf(userid)) 
	   *  
	   *  EhcacheUtils.getInstance().put(CACHE_NAME,userid,user)
	   *  
	   *  System.out.println("user-"+user)
	   *  
	   *  GET 获取缓存的数据
	   *  
	   *  User user=(User)EhcacheUtils.getInstance.get(CACHE_NAME,id)
	   *  
	   *     
	   *      
	   *   
	   *      
	   */
	  public void put(String cacheName, String key, Object value) {
	    Cache cache = cacheManager.getCache(cacheName);
	    Element element = new Element(key, value);
	    cache.put(element);
	  }
	 
	  /**
	   * 获取一个缓存的对象，没有返回NULL
	   * 
	   * @param cacheName
	   * @param key
	   * @return
	   */
	  public Object get(String cacheName, String key) {
	    Cache cache = cacheManager.getCache(cacheName);
	    Element element = cache.get(key);
	    return element == null ? null : element.getObjectValue();
	  }
	 
	  public Cache get(String cacheName) {
	    return cacheManager.getCache(cacheName);
	  }
	 
	  public void remove(String cacheName, String key) {
	    Cache cache = cacheManager.getCache(cacheName);
	    cache.remove(key);
	  }
	
	public Cache getOrAddCache(String cacheName) {
		Boolean locker=true;
	    Cache cache = cacheManager.getCache(cacheName);
	    if (cache == null) {//locker
	        synchronized (locker) {
	            cache = cacheManager.getCache(cacheName);
	            if (cache == null) {
	            	cacheManager.addCacheIfAbsent(cacheName);
	                cache = cacheManager.getCache(cacheName);
	            }
	        }
	    }
	    return cache;
	}
	
	public Boolean Exists(String key,String cacheName){
	Cache cache = getOrAddCache(cacheName);
	if(cache.isKeyInCache(key) && cache.getQuiet(key) != null){
	    return true;
	}
	return false;
	}
}
